package cn.onein.edu.web.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import cn.onein.edu.biz.bean.LearnContent;
import cn.onein.edu.biz.bean.SharedActions;
import cn.onein.edu.biz.bean.User;
import cn.onein.edu.biz.bean.UserDailyAction;
import cn.onein.edu.util.DateUtil;
import cn.onein.edu.web.common.base.BaseController;
import cn.onein.edu.web.jms.producer.SendMailProducer;
import cn.onein.edu.web.service.LearnContentService;
import cn.onein.edu.web.service.UserCenterService;
import cn.onein.edu.web.util.AjaxCallBackJsonUtil;
import cn.onein.edu.web.vo.AjaxCallbackVO;
import cn.onein.edu.web.vo.DailyActionVO;

/**
 * 用户分享行动指南控制器
 * 
 * @author Upton
 * 
 */
@Controller
public class ShareUserActionController extends BaseController {
	Logger logger = Logger.getLogger(ShareUserActionController.class);

	@Autowired
	private UserCenterService userCenterService;

	@Autowired
	private SendMailProducer sendMailProducer;
	
	@Autowired
	private LearnContentService learnContentService;
	
	/**
	 * 显示一条用户分享的行动指南页面
	 * 
	 * @param uuid
	 * @return
	 */
	@RequestMapping(value = "/share/{uuid}.jhtml", method = {
			RequestMethod.GET, RequestMethod.POST })
	public ModelAndView content(@PathVariable String uuid,HttpServletRequest req) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		ModelAndView mv = new ModelAndView("share/shareUserAction");
		Map<String, Object> param = new HashMap<String, Object>();

		if (uuid == null || "".equals(uuid.trim())) {
			return new ModelAndView("resourceNotFound");
		}

		SharedActions shareAction = userCenterService.getShareActionByUUID(uuid);
		if (shareAction == null) {
			return new ModelAndView("resourceNotFound");
		}
		
		User user = userCenterService.getUserById(shareAction.getUserId());
		if (user == null) {
			return new ModelAndView("resourceNotFound");
		}

		UserDailyAction userAction = userCenterService.getDailyAction(shareAction.getUserId(),
						df.format(shareAction.getActionDate()));
		if (userAction == null) {
			return new ModelAndView("resourceNotFound");
		}
		
		DailyActionVO vo = this.convertDailyActionVO(userAction,shareAction);
		
		String shareUrl = req.getRequestURL().toString();
		
		List<LearnContent> contents = learnContentService.getHotContentByHits(12);
		
		param.put("userAction", vo);
		param.put("shareAction", shareAction);
		param.put("user", user);
		param.put("shareUrl", shareUrl);
		
		param.put("contents", contents);
		
        mv.addAllObjects(param);
        
		setMenu(mv, MENU_VALUE_SHARE_ACTION);

		return mv;
	}
	
	/**
	 * 将该文章分享朋友
	 * 
	 * @return
	 */
	@RequestMapping(value = "/share/sendMail.json", method = { RequestMethod.GET,
			RequestMethod.POST })
	public void sendMail( String emails,String shareUrl,HttpServletResponse resp,HttpServletRequest req)
			throws Exception {

		if(null == emails || "".equals(emails)){
			return;
		}
		
		String[] mailArray = emails.split(";");
		for(String mail : mailArray ){
			try{
				if(mail != null && mail.trim().length() > 0){
					sendMailProducer.sendShareActionMailMessage(mail.trim(), shareUrl);
				}
			}catch(Exception e){
		        logger.error("send mail fail: " + mail,e);
		        AjaxCallBackJsonUtil.callbackJSON(new AjaxCallbackVO(AJAXERROR), resp);
		        return;
			}
		}
		
		AjaxCallBackJsonUtil.callbackJSON(new AjaxCallbackVO(AJAXSUCCESS), resp);
	}

	/**
	 * 数据格式化输出
	 * 
	 * @param dailyActions
	 * @return
	 */
	private DailyActionVO convertDailyActionVO(UserDailyAction dailyAction,SharedActions shareAction) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		DailyActionVO vo = new DailyActionVO();

		vo.setIntroText(dailyAction.getIntroText());
		if (dailyAction.getActive()) {
			vo.setFullText(dailyAction.getFullText());
		}
		Date actionDate = dailyAction.getActionDate();
		String strDate = df.format(actionDate);
		vo.setDate(strDate.substring(5, 10));
		vo.setWeek(DateUtil.getWeekOfDate(actionDate));
		vo.setDailyNote(dailyAction.getDailyNote());
		vo.setActionDate(df.format(dailyAction.getActionDate()));
		vo.setActionResult(dailyAction.getActionResult());
		if(shareAction.getShareActionBaby() != null && shareAction.getShareActionBaby() == true){
			vo.setBabyDaily(dailyAction.getBabyDaily());
		}
		
		return vo;
	}
}
